<?php
namespace app\http\middleware;
use think\Controller;
use auth\Action;
use base\BaseMethod;
use auth\Auth;

/**
* token验证中间件
* Class AuthTokenMiddleware
* @package app\http\middleware
*/
class AuthTokenWeb extends Controller
{
	public  		 $errorInfo;   			//错误信息
	public  		 $userInfo; 				//当前登录账号信息
	public  		 $userAction; 			//当前用户所拥有的授权
	protected  $isLogin; 					//是否登录
	protected  $isAllowPath; 			//白名单接口
	protected  $activeUrl; 				//当前接口地址
	
	//自执行中间件方法
   	public function handle($request, \Closure $next){
       //如果是支付模块
        if( strstr( request()->path(),"system/payment") ){
            return $next($request);
        } 
        
		//当前接口地址
		$this->activeUrl = strtolower( get_active_url() );
        
   		//路由白名单
		$this->isAllowPath =  in_array( $this->activeUrl , ['admin/soft.1/login','wx/inlet'] );
        
		//登录情况
		$this->isLogin = $this->isLogin();
		
		//验证入口权限
		if( !$this->is_exist_index_auth() ){
			return $this->fetch("layout/default");
		}
		
		//验证店长信息
		if( !$this->is_perfect_shop_info() ){
			$this->assign('userInfo', $this->userInfo );
			return $this->fetch("modules/shop/index");
		}
		
		//检测所有请求参数是否有sql注入的风险
		if( $this->is_exist_sql_inject() ){
			return BaseMethod::ReError("监听到存在SQL注入的风险</br>请调整后重新操作！",-2);
		}
 
		//效验接口登录情况
		$desc = get_method_desc();
		$method = strtolower($desc['method']);
		if( $method !='all' && strtolower($request->method()) != $method){
			return BaseMethod::ReError("不允许".strtolower($request->method()).'请求！');
		}
		if ($desc['is_need_login'] !='false' && !$this->isAllowPath && !$this->isLogin ){
			return BaseMethod::ReError($this->errorInfo,-10);
		}

		//判断当前用户的当前请求	地址是否有权限
		if($this->userInfo['is_admin'] != 1 && !$this->isAllowPath && !$this->is_exist_action_auth()){
			if(Config('app_debug')==true) dump($this->userAction);
			return BaseMethod::ReError("没有该操作的权限！", -2 );
		}
		$request->userInfo = $this->userInfo;
		$request->userId = $this->userInfo['user_id'];
		$request->userAction = $this->userAction;
		$request->shopId = $this->userInfo['shop_id'];
		
        return $next($request);
    }
    
    
    /**
     * 如果是店长登录-是否已完善店长信息
     * @return boolean
     */
	private function is_perfect_shop_info(){
		if( strstr(request()->header()['referer'],'modules/shop/list/edit') ){
			return true;
		}
		$url = request()->path();
		$url = urldecode( count(explode('/',$url) ) > 1 ? $url : "modules/index/index" );
		//如果是店长登录-并未完成信息，则跳转到信息补充页
		if($this->userInfo['shop_id'] > 0 && $url != 'modules/shop/list/edit'){
			$shop = model('common/shop')->get($this->userInfo['shop_id']);
    		if( !$shop->name ){
    			return false;
    		}
    	}
		return true;
	}
    
	
	/**
     * 如果是入口，未登录，则跳转到登录页
     * @return boolean
     */
	private function is_exist_index_auth(){
		//解码当前路由
		$url = request()->path();
		$url = urldecode(count(explode('/',$url)) > 1 ? $url : "modules/index/index");
		if($this->activeUrl == 'admin/soft.index/index'){
			if( !$this->isLogin && $url != "layout/default"){
				return false;
			}	
			//验证授权
			if( $this-> userInfo["roles"] !=1){
				if( !in_array($this->activeUrl,'modules/index/index' )  && !$this->is_exist_user_auth($url) ){
					return (new BaseMethod)->ReError('404：无访问权限！');
				}
			}
		}
		return true;
	}
	
	/**
     * 验证用户访问权限
     * @return boolean
     */
    private function is_exist_user_auth($url){
		$auths = model('SystemNav') -> getNavAuthCode($url);
		if($auths['func_code'] || $auths['func_code']=='0'){
			$this->userAction = $is = Action::instance($this->userInfo)->check( $auths['func_code'] ,'00' );
			return $is;
		}
		return true;
    }
	
	/**
     * 验证访问接口权限
     * @return boolean
     */
	private function is_exist_action_auth(){
		$func_code = $this->desc['func_code'];
		$action_code = $this->desc['action_code'];
		if( !empty($func_code)  && !empty($action_code) || $func_code== '0' || $action_code=='0'){
			$this->userAction = $is = Action::instance($this->userInfo)->check( $func_code , $action_code );
		}
		return true;
	}
	
	/**
     * 验证登录
     * @return boolean
     */
    public function isLogin()
    {
    	
		$this->userInfo = $userInfo = action('admin/soft/Auth/getUserInfo'); 
		if ( empty( $userInfo ) ) {
			$this->errorInfo = '登录异常，请重新登录！';
            return false;
        }
		if ( "1" != $userInfo['land_status'] ) {
            $this->errorInfo = '登录状态已被改为未登录！';
            return false;
        }
        if ( "0" == $userInfo['is_enable'] ) {
            $this->errorInfo = '您的帐号已经被禁用！';
            return false;
        }
		return true;
    }
	
	//<!--  = 检测是否存在sql注入 =  -->
	private function is_exist_sql_inject(){
		$pattern='/\binsert\s|\bselect\s|\bupdate\s|\bdelete\s|\bcreate\s|\balter\s|\bdrop\s|(\bexec|\bexecute)[\s\(]|\bsp_|\bxp_|\sinto\s/';
		$param =  strtolower(  json_encode($_REQUEST) );
		return preg_match($pattern,$param) ? true : false;
    }
	
	//<!--  = 检测是否村在特殊符号 =  -->
	private function is_exist_special_symbols(){
		$pregs = '/\*|\#/';
		$param =  strtolower(  json_encode($_REQUEST) );
		return preg_match($pregs,$param) ? true : false;
    }
	

}